<template>
  <div>
    <div id="main1" style="width: 45vw; height: 35vh; margin-top: 20px"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { watch, ref } from 'vue';
const props = defineProps({
  chartsData: {
    type: Object,
    default: () => {},
  },
});
const seriesConfig = ref(null);
const newChartsData = ref({});
const legendArr = ref([]);
watch(
  () => props.chartsData,
  (newValue) => {
    if (newValue) {
      newChartsData.value = newValue;
      // 清空 legendArr 并重新填充
      legendArr.value = Object.keys(newChartsData.value.users.series);
      // 创建 series 配置项数组
      seriesConfig.value = legendArr.value.map((key, index) => ({
        name: key,
        type: 'line',
        stack: 'Total',
        symbolSize: 0,
        data: newChartsData.value.users.series[key],
        itemStyle: {
          color:
            newChartsData.value.users.colors[
              index % newChartsData.value.users.colors.length
            ],
        },
      }));
      // 调用处理函数更新图表
      handleBarChart();
    }
  }
);

const handleBarChart = () => {
  let chartDom = document.getElementById('main1');
  let myChart = echarts.init(chartDom);
  let option;

  option = {
    // title: {
    //   text: newChartsData.value.users.title,
    // },
    tooltip: {
      trigger: 'axis',
      position: function (point, params, dom, rect, size) {
        //  size为当前窗口大小
        if (size.viewSize[0] / 2 >= point[0]) {
          //其中point为当前鼠标的位置
          return [point[0] + 50, '10%'];
        } else {
          //其中point为当前鼠标的位置
          return [point[0] - 200, '10%'];
        }
      },
    },
    legend: {
      data: legendArr.value,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    // toolbox: {
    //   feature: {
    //     saveAsImage: {},
    //   },
    // },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: newChartsData.value.users.xAxis,
    },
    yAxis: {
      type: 'value',
    },
    series: seriesConfig.value,
  };

  option && myChart.setOption(option);
};
</script>

<style lang="scss" scoped></style>
